package org.qb.mapreduce.partitionerSort;

import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * 1、定义类实现WritableComparable
 * 2、重写序列化，反序列化方法
 * 3、重写空参构造
 * 4、重写ToString方法，打印输出
 * 5、重寫compareTo方法，進行重排序
 */
public class FlowBean implements WritableComparable<FlowBean> {

    private long upFlow;//上行流量
    private long downFlow;//下行流量
    private long sumFlow;//总流量


    public long getUpFlow() {
        return upFlow;
    }

    public void setUpFlow(long upFlow) {
        this.upFlow = upFlow;
    }

    public long getDownFlow() {
        return downFlow;
    }

    public void setDownFlow(long downFlow) {
        this.downFlow = downFlow;
    }

    public long getSumFlow() {
        return sumFlow;
    }

    public void setSumFlow(long sumFlow) {
        this.sumFlow = sumFlow;
    }

    public void setSumFlow() {
        this.sumFlow = this.upFlow + this.downFlow;
    }

    //空参构造啦
    public FlowBean() {
    }

    /**
     * write重写方法中定义序列化的顺序
     * @param dataOutput
     * @throws IOException
     */
    @Override
    public void write(DataOutput dataOutput) throws IOException {
        dataOutput.writeLong(upFlow);
        dataOutput.writeLong(downFlow);
        dataOutput.writeLong(sumFlow);
    }

    /**
     * 反序列化中定义的顺序要跟序列化的一致
     * @param dataInput
     * @throws IOException
     */
    @Override
    public void readFields(DataInput dataInput) throws IOException {

        this.upFlow = dataInput.readLong();
        this.downFlow = dataInput.readLong();
        this.sumFlow = dataInput.readLong();
    }


    @Override
    public String toString() {
        return  upFlow +
                " " + downFlow +
                " " + sumFlow ;
    }


    @Override
    public int compareTo(FlowBean o) {

        //總流量的倒序排序
        if (this.sumFlow > o.sumFlow){
            return -1;
        } else if (this.sumFlow < o.sumFlow) {
            return 1;
        }else {
            //upflow filed 以正序排序
            return Long.compare(this.upFlow, o.upFlow);
        }
    }
}
